/*
 * Copyright (C) 2010 Zaizi Limited.
 * 
 * This file is part of Zaizi's Alfresco FISE integration
 * 
 * Alfresco FISE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Alfresco FISE is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Alfresco FISE. If not, see <http://www.gnu.org/licenses/>.
 */
package org.zaizi.fiseiks.alfresco.service;

import javax.ws.rs.core.MediaType;

import org.alfresco.model.ContentModel;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.service.cmr.repository.ContentReader;
import org.alfresco.service.cmr.repository.ContentService;
import org.alfresco.service.cmr.repository.ContentWriter;
import org.alfresco.service.cmr.repository.NodeRef;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.sun.jersey.api.client.ClientResponse;

/**
 * Implements {@link FiseIksPublishService}
 * 
 * @author apillai
 * @author efoncubierta
 * @see FiseIksAbstractService
 */
public class FiseIksPublishServiceImpl extends FiseIksAbstractService implements FiseIksPublishService
{
    private Log logger = LogFactory.getLog(FiseIksPublishServiceImpl.class);
    
    private ContentService contentService;
    
    /**
     * Initialization method
     */
    public void init() {
    	contentService = getServiceRegistry().getContentService();
    }
    
    /*
     * (non-Javadoc)
     * @see org.zaizi.fiseiks.alfresco.service.FiseIksPublishService#postContent(org.alfresco.service.cmr.repository.NodeRef)
     */
    public void postContent(NodeRef nodeRef)
    {
        String storeContentUrl = FISE_STORE_CONTENT + "/" + nodeRef.getId();
        
        ContentReader reader = getTextContentReader(nodeRef);
        
        ClientResponse response = getRestClient().put(storeContentUrl,
        		reader.getContentInputStream(),
        		MediaType.TEXT_PLAIN_TYPE, MediaType.WILDCARD_TYPE);
        
        int status = response.getStatus();
        if(status != 200 && status != 201 && status != 202) {
        	logger.error("Error while posting content " + nodeRef + " to Fise at " + storeContentUrl);
        } else {
        	logger.debug("Successfully posted " + nodeRef + " to " + storeContentUrl);
        }
    }
    
    /**
     * Get a content reader from a nodeRef. If content mimetype isn't
     * text/plain, convert it
     * 
     * @param nodeRef Node reference
     * @return Content reader
     */
    private ContentReader getTextContentReader(NodeRef nodeRef)
    {
        ContentReader reader = contentService.getReader(nodeRef, ContentModel.PROP_CONTENT);
        
        if (MimetypeMap.MIMETYPE_TEXT_PLAIN.equals(reader.getMimetype()))
        {
            return reader;
        }
        else
        {
            ContentWriter writer = contentService.getWriter(null, ContentModel.PROP_CONTENT, true);
            writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN); 
            writer.setEncoding(reader.getEncoding());
            
            // try and transform the content
            if (this.contentService.isTransformable(reader, writer))
            {
                this.contentService.transform(reader, writer);
                
                ContentReader resultReader = writer.getReader();
                return resultReader;
            }
            return null;
        }
    }
}
